package com.fengzuxiao.weatherdemo;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.fengzuxiao.weatherdemo.db.DBHelper;

/**
 * Created by 17929 on 2020/6/14.
 */

public class UserService {
    public static SQLiteDatabase db;

    //初始化数据库信息
    public UserService(Context context) {
        DBHelper dbHelper = new DBHelper(context);
        db = dbHelper.getReadableDatabase();
    }

    public boolean login(String username, String password) {
        String sql = "select * from user where username=? and password=?";
        Cursor cursor = db.rawQuery(sql, new String[]{username, password});
        if (cursor.moveToFirst()==true ) {
            cursor.close();
            return true;
        }
        return false;
    }

    public boolean register(User user) {
        Cursor c = db.rawQuery("select * from user where username=?", new String[]{user.getUsername()});
        if (c != null && c.getCount() > 0) {

            c.close();
            return false;
        } else {
            String sql = "insert into user(username,password) values(?,?)";
            Object obj[] = {user.getUsername(), user.getPassword()};
            db.execSQL(sql, obj);
            return true;
        }

    }

    public boolean update(User user) {
        Cursor change = db.rawQuery("select * from user where username=? ", new String[]{user.getUsername()});
        if (change != null && change.getCount() > 0) {

            String sql = "UPDATE user SET password =? ";
            Object obj[] = new String[]{user.getPassword()};
            db.execSQL(sql, obj);
            return true;
        }
        return false;

    }

}

